import React, { Component } from 'react'
import { Button, Form, Row, Col, message, Modal, Spin, Alert,Tree,Input,Checkbox,Table } from 'antd';
import EditableCell from './EditableCell1'
import { fetchData  } from "../../../components/AjaxConsumer";
import styles from './DateText.scss';

const TreeNode = Tree.TreeNode;
const Search = Input.Search;


export default class DataText extends Component {
    constructor(props) {
        super(props);
        this.state = {
            resData: null,
            gData: [],//数据字典一级数据
            dicTitle: '',//数据字典一级标题
            count: 1,//新添加的行的主键
            dicTypeCode: null,//新增外间
            dataChild: [],//数据字典二级数据
            selectedRowKeys: [],//选中二级列表行数据
            selectedRows: [], //选中二级列表行数据对象s
            editable: false,//用来标志显示右侧应该显示什么内容
            alertType: 'info',//Alert显示的类型
        };

        this.columns = [
            {
                title: '条目编码',
                dataIndex: 'dicCode',
                width: '20%',
                render: (text, record, index) => this.renderColumns(this.state.dataChild, index, 'dicCode', text),
            }, {
                title: '条目值',
                dataIndex: 'dicName',
                width: '30%',
                render: (text, record, index) => this.renderColumns(this.state.dataChild, index, 'dicName', text),
            }, {
                title: '字典类型',
                dataIndex: 'dicType',
                width: '30%',
                render: (text, record, index) => this.renderColumns(this.state.dataChild, index, 'dicType', text),
            }, {
                title: '排序号',
                dataIndex: 'sequenceNumber',
                width: '10%',
                render: (text, record, index) => this.renderColumns(this.state.dataChild, index, 'sequenceNumber', text),
            }, {
                title: '激活标志',
                dataIndex: 'activeFlag',
                width: '10%',
                render: (text, record, index) => (

                    //三元运算 如果 activeFlag=1 时 启用  activeFlag=0 时 停用
                    text == 0 ? (
                        <span>禁用</span>
                    ) : (
                        <span>启用</span>
                    )
                ),
            }, {
                title: '编辑',
                dataIndex: 'operate',
                width: '10%',
                render: (text, record, index) => {
                    const { editable } = this.state.dataChild[index];
                    return (
                        editable ?
                        <span style={{color: '#108ee9'}}>
                            <a style={{color: '#108ee9'}} onClick={() => this.editDone(index)}>暂存</a>
                        </span>
                        :
                        <span style={{color: '#9E9E9E'}}>
                          <a style={{color: '#9E9E9E'}} onClick={() => this.edit(index)}>编辑</a>
                        </span>
                    );
                }
            }
        ];
    }

    renderColumns(data, index, key, text) {
        const { editable, status } = data[index];
        if (typeof editable === 'undefined') {
            return text;
        }
        return (<EditableCell
            editable={editable}
            value={text}
            onChange={value => this.handleChange(key, index, value)}
            status={status}
        />);
    }

    handleChange(key, index, value) {
        const { dataChild } = this.state;
        dataChild[index][key] = value;
        this.setState({ dataChild:  dataChild});
    }

    datasubbmit(){
        console.log("dataChild: " + JSON.stringify(this.state.dataChild));
        let options = {
            url: '/base/dic/u/batch',//请求地址
            type: 'post',//请求方式
            condition: JSON.stringify(this.state.dataChild),//请求条件
            contentType: 'application/json;charset=utf-8'
        };
        fetchData(this, options, (resData) => {
            console.log("subbi resData:" + JSON.stringify(resData.code));
            if (resData.code == "1") {
                message.success('保存成功!');
            } else {
                message.error("请求数据错误：" + resData.message);
            }
        });

    }

    edit(index) {
        const { dataChild } = this.state;
        dataChild[index].editable = true;
        dataChild[index].status = 'edit';
        this.setState({ dataChild });
    }

    editDone(index) {
        const { dataChild } = this.state;
        dataChild[index].editable = false;
        dataChild[index].status = 'save';
        this.setState({ dataChild });
    }

    //【左侧字典树】请求数据，刷新函数
    refleshData = () => {
        //发送ajax请求基础树数据
        let options = {
            url: '/base/dic/list/dicType',        //请求地址
            type: 'post',    //请求方式
            condition: {},
        };
        fetchData(this, options, (resData) => {
            console.log("refleshData resData:" + JSON.stringify(resData.data));
            this.setState({
                //过滤掉 dicTypeCode 为null或""
                //gData: resData.data.records.filter(item => item.dicType === ""||item.dicType === null)
                gData: resData.data
            });
        });
    }

    componentDidMount() {
        this.refleshData();
    }

    //【左侧字典树】选中一级列表
    onSelect = (selectedKeys, info) => {
        console.log('selected', selectedKeys, info);
        this.setState({editable: true});//显示出表格内容
        let dicType = selectedKeys[0];
        //console.log('dicType', dicType);
        if (dicType) {//不等于空的时候发起请求
            let title = info.selectedNodes[0].props.title;//获取一级字典名称，用来展示到右侧的标题
            //console.log('title', title);
            let options = {//发起请求的连接对象
                url: '/base/dic/list/all',        //请求地址
                type: 'post',    //请求方式
                condition: {dicType: dicType},//传参
            };
            fetchData(this, options, (resData) => {//掉ajav请求
                console.log("具体Data=====:" + JSON.stringify(resData));
                this.setState({
                    dataChild: resData.data,
                    dicTitle: title,
                    dicTypeCode: dicType
                });
            });
        }

    }

    //【左侧字典树】查询条件
    onChangeSearch = (e) => {
        const value = e.target.value;
        let options = {
            url: '/base/dic/list/dicType',        //请求地址
            type: 'post',    //请求方式
            condition: {dicTypeDesc: value},
        };
        fetchData(this, options, (resData) => {
            console.log("Data=====:" + JSON.stringify(resData.data));
            this.setState({
                //过滤掉 dicTypeCode 为null或""
                //gData: resData.data.records.filter(item => item.dicTypeCode === ""||item.dicTypeCode === null)
                gData: resData.data
            });
        });
    }

    //添加项目
    handleAdd = () => {
        const { count, dataChild, dicTypeCode, dicTitle,alertType } = this.state;
        if (dicTitle) {
            const newData = {
                dicCode: count,
                dicName: `新增对象 ${count}`,
                dicType: dicTypeCode,
                dicTypeDesc: dicTitle,
                activeFlag: '1',
            };
            this.setState({
                dataChild: [...dataChild, newData],
                count: count + 1,
            });

        } else {
            this.setState({alertType: 'warning'});
        }
    }

    //停用和启用方法
    handleActive = (flag) => {//flag=1为启用 flag=0为停用
        const { selectedRowKeys, selectedRows, dataChild} = this.state;
        if (selectedRowKeys.length == 1) {//判断选择时才能点击按钮
            let dictionaryId = selectedRowKeys[0];
            console.log("dictionaryId==============================:" + JSON.stringify(dictionaryId));
            let options = {
                url: '/base/dic/u',        //请求地址
                type: 'post',    //请求方式
                condition: {dictionaryId: dictionaryId, activeFlag: flag},
            };
            fetchData(this, options, (resData) => {
                if (resData.code == "1") {
                    dataChild.map((item, index) => {
                        if (dataChild[index].dictionaryId == selectedRowKeys[0]) {
                            console.log(dataChild[index].dictionaryId);
                            dataChild[index].activeFlag = flag
                            this.setState({
                                selectedRowKeys: [],
                                dataChild: [...dataChild]
                            });
                        }
                    });
                }
            });
        }
        else {
            Modal.error({
                title: '错误提示',
                content: '请选择一条数据',
            });
        }
    }

    render() {
        //表格数据
        const columns = this.columns;
        const {dataChild, gData, dicTitle, editable, alertType,selectedRowKeys} = this.state;
        //循环一级列表
        const loop = data => data.map((item, index) => {
            return (
                <TreeNode key={item.dicType} title={item.dicTypeDesc}>
                </TreeNode>
            );

        });

        //表格复选框
        const rowSelection = {
            onChange: (selectedRowKeys, selectedRows, getCheckboxProps) => {
                console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', getCheckboxProps);
                this.setState({
                    selectedRowKeys: selectedRowKeys,
                    selectedRows: selectedRows
                });
            },
            onSelect: (record, selected, selectedRows, getCheckboxProps) => {
                console.log(record, selected, selectedRows, getCheckboxProps);
            },
            selectedRowKeys,


        };

        return (
            <div className={styles.formBoxStyle}>

                <Row gutter={16} style={{height:'100%'}}>
                    <Col span={8} style={{height:'100%'}}>
                        <div className={styles.dataMain}>
                            <h2 className={styles.dataTitle}>字典类型</h2>
                            <Search className={styles.search} placeholder="查询"
                                    onChange={value => this.onChangeSearch(value)}/>
                            <div style={{height:'450px',overflowY:'scroll'}}>
                            <Tree
                                onSelect={this.onSelect}
                            >
                                {loop(gData)}
                            </Tree>
                            </div>
                        </div>
                    </Col>

                    <Col span={16} style={{height:'100%'}}>
                        <div className={styles.dataMain}>
                            <h2 className={styles.dataTitle}>{dicTitle}</h2>
                            <div className={styles.dataCaozuo}>
                                <Row>
                                    <Col span={16} offset={14}>
                                        <Button type="primary" onClick={this.handleAdd}>新增</Button>
                                        <Button type="primary" onClick={()=>{this.handleActive("0")}}
                                                style={{margin:'0px 0px 0px 10px'}}>停用</Button>
                                        <Button type="primary" onClick={()=>{this.handleActive("1")}}
                                                style={{margin:'0px 0px 0px 10px'}}>启用</Button>
                                        <Button type="primary" onClick={()=>{this.datasubbmit()}}
                                                style={{margin:'0px 0px 0px 10px'}}>提交</Button>
                                    </Col>
                                </Row>
                            </div>
                            <div style={{margin: '10px'}}>
                                {
                                    editable ?
                                        <Table rowSelection={rowSelection}
                                               columns={columns}
                                               dataSource={dataChild}
                                               rowKey={row => row.dictionaryId}
                                            //showHeader={false}
                                               pagination={false}
                                               size="middle"
                                        />
                                        :
                                        <Alert
                                            style={{marginRight:'50px'}}
                                            message="温馨提示"
                                            description="操作前，请先点击选择左侧需要选择的节点"
                                            type={alertType}
                                            showIcon
                                        />

                                }
                            </div>
                        </div>
                    </Col>
                </Row>
            </div>
        );
    }

}
